package com.sheliduan.itlearning.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sheliduan.itlearning.admin.model.vos.home.DailyIncomeVO;
import com.sheliduan.itlearning.admin.model.vos.home.HomeStatisticsRspVO;
import com.sheliduan.itlearning.common.domain.dos.ArticleCourseDO;
import com.sheliduan.itlearning.common.domain.dos.OrderDO;
import com.sheliduan.itlearning.common.domain.dos.UserDO;
import com.sheliduan.itlearning.common.domain.dos.VideoCourseDO;
import com.sheliduan.itlearning.common.domain.mapper.ArticleCourseMapper;
import com.sheliduan.itlearning.common.domain.mapper.OrderMapper;
import com.sheliduan.itlearning.common.domain.mapper.UserMapper;
import com.sheliduan.itlearning.common.domain.mapper.VideoCourseMapper;
import com.sheliduan.itlearning.common.utils.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/home")
public class AdminHomeController {

    @Autowired
    private ArticleCourseMapper articleCourseMapper;

    @Autowired
    private VideoCourseMapper videoCourseMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;

    private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("MM-dd");

    @GetMapping("/statistics")
    public ResponseData getHomeStatistics() {
        // 1. 统计图文课程数量（status为2或4）
        Long articleCount = articleCourseMapper.selectCount(new LambdaQueryWrapper<ArticleCourseDO>()
                .in(ArticleCourseDO::getStatus, 2, 4));

        // 2. 统计视频课程数量（status为2或4）
        Long videoCount = videoCourseMapper.selectCount(new LambdaQueryWrapper<VideoCourseDO>()
                .in(VideoCourseDO::getStatus, 2, 4));

        // 3. 统计用户数量（role为USER）
        Long userCount = userMapper.selectCount(new LambdaQueryWrapper<UserDO>()
                .eq(UserDO::getRole, "USER"));

        // 4. 统计博主数量（role为BLOGGER）
        Long bloggerCount = userMapper.selectCount(new LambdaQueryWrapper<UserDO>()
                .eq(UserDO::getRole, "BLOGGER"));

        // 5. 统计近30天每日收益
        Calendar calendar = Calendar.getInstance();
        Date endDate = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, -29);
        Date startDate = calendar.getTime();

        // 查询30天内的所有订单
        List<OrderDO> orders = orderMapper.selectList(new LambdaQueryWrapper<OrderDO>()
                .ge(OrderDO::getOrderTime, startDate)
                .le(OrderDO::getOrderTime, endDate));

        // 按日期分组统计收益
        Map<String, Double> dailyIncomeMap = orders.stream()
                .collect(Collectors.groupingBy(
                        order -> DATE_FORMATTER.format(order.getOrderTime()),
                        Collectors.summingDouble(OrderDO::getPrice)
                ));

        // 生成30天的日期列表，确保没有订单的日期也显示为0
        List<DailyIncomeVO> dailyIncomes = new ArrayList<>();
        calendar.setTime(startDate);
        for (int i = 0; i < 30; i++) {
            String dateStr = DATE_FORMATTER.format(calendar.getTime());
            double income = dailyIncomeMap.getOrDefault(dateStr, 0.0);
            dailyIncomes.add(DailyIncomeVO.builder()
                    .date(dateStr)
                    .income(income)
                    .build());
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        // 构建返回对象
        HomeStatisticsRspVO rspVO = HomeStatisticsRspVO.builder()
                .articleCount(articleCount)
                .videoCount(videoCount)
                .userCount(userCount)
                .bloggerCount(bloggerCount)
                .dailyIncomes(dailyIncomes)
                .build();

        return ResponseData.success(rspVO);
    }
}